package net.csdn.business.discuss.api.service.impl;

import java.util.List;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.discuss.api.mapper.DiscussCategoryMapper;
import net.csdn.business.discuss.api.mapper.DiscussSectionMapper;
import net.csdn.business.discuss.api.model.dto.DeleteResourceDTO;
import net.csdn.business.discuss.api.model.dto.NewDiscussSectionDTO;
import net.csdn.business.discuss.api.model.dto.UpdateAuditStatusDTO;
import net.csdn.business.discuss.api.model.dto.UpdateDiscussSectionDTO;
import net.csdn.business.discuss.api.model.entity.Discuss;
import net.csdn.business.discuss.api.model.entity.DiscussCategory;
import net.csdn.business.discuss.api.model.entity.DiscussSection;
import net.csdn.business.discuss.api.model.query.DiscussSectionQuery;
import net.csdn.business.discuss.api.model.vo.DiscussCategoryVO;
import net.csdn.business.discuss.api.model.vo.DiscussSectionVO;
import net.csdn.business.discuss.api.service.IDiscussSectionService;
import net.csdn.business.discuss.common.constant.RedisConstants;
import net.csdn.business.discuss.common.enums.ResultCodeEnum;
import net.csdn.business.discuss.common.exception.BusinessException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 讨论类型分组Service业务层处理
 * 
 * @author Admin Cloud
 * @date 2023-07-15
 */
@Slf4j
@Service
public class DiscussSectionServiceImpl extends ServiceImpl<DiscussSectionMapper, DiscussSection> implements IDiscussSectionService
{


    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private DiscussCategoryMapper discussCategoryMapper;

    /**
     * 分页查询讨论类型分组列表
     *
     * @param query 讨论类型分组
     * @return 讨论类型分组
     */
    @Override
    public Page<DiscussSectionVO> findPageList(DiscussSectionQuery query) {
        //获得Page对象
        Page<DiscussSectionVO> page = query.getPage();
        List<DiscussSectionVO> pageList=baseMapper.findPageList(page,query);
        page.setRecords(pageList);
        return page;
    }

    /**
     * 根据id查询讨论类型分组
     * 
     * @param id 讨论类型分组主键
     * @return 讨论类型分组
     */
    @Override
    public DiscussSectionVO selectDiscussSectionById(String id)
    {
        DiscussSectionVO result= baseMapper.selectDiscussSectionById(id);
        return result;
    }

    /**
     * 根据id查询讨论类型分组，以及分组下的类别
     *
     * @param id 讨论类型分组主键
     * @return 讨论类型分组
     */
    @Override
    public DiscussSectionVO selectDiscussSectionDetail(String id)
    {
        DiscussSectionVO result= baseMapper.selectDiscussSectionById(id);
        if(result==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        //根据sectionId查询分类
        List<DiscussCategoryVO> categoryList =discussCategoryMapper.getListBySectionId(id);
        result.setCategoryList(categoryList);
        return result;
    }

    @Override
    public List<DiscussSectionVO> selectDiscussSectionListBySourceId(String sourceId) {
        return baseMapper.selectDiscussSectionListBySourceId(sourceId);
    }

    /**
     * 查询讨论类型分组列表
     * 
     * @param query 讨论类型分组
     * @return 讨论类型分组
     */
    @Override
    public List<DiscussSectionVO> selectDiscussSectionList(DiscussSectionQuery query)
    {
        return baseMapper.selectDiscussSectionList(query);
    }

    /**
     * 新增讨论类型分组
     * 
     * @param params 讨论类型分组
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertDiscussSection(NewDiscussSectionDTO params)
    {
        String sourceId=params.getSourceId();
        String currUserId=params.getCurrUserId();
        //验证section的名称是否存在
        LambdaQueryWrapper<DiscussSection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DiscussSection::getSectionName, params.getSectionName());
        queryWrapper.eq(DiscussSection::getSourceId,params.getSourceId());
        List<DiscussSection> sections=baseMapper.selectList(queryWrapper);
        if(sections!=null&&sections.size()>0){
            throw new BusinessException(ResultCodeEnum.DISCUSS_SECTION_NAME_EXIST_ERROR);
        }
        DiscussSection discussSection=new DiscussSection();
        BeanUtils.copyProperties(params,discussSection);
        String id= IdUtil.fastSimpleUUID();
        discussSection.setObjectId(id);
        discussSection.setCreatedBy(currUserId);
        int result=baseMapper.insert(discussSection);
        List<String> categoryIdList=params.getCategoryIdList();
        if(categoryIdList!=null){
            categoryIdList.stream().parallel().forEach(categoryId->{
                LambdaUpdateWrapper<DiscussCategory> updateWrapper = new UpdateWrapper<DiscussCategory>().lambda();
                updateWrapper.eq(DiscussCategory::getObjectId, categoryId);
                DiscussCategory discussCategory=new DiscussCategory();
                discussCategory.setSectionId(id);
                discussCategoryMapper.update(discussCategory,updateWrapper);
            });
        }
        Cache cache=null;
        try{
            cache = cacheManager.getCache(RedisConstants.DISCUSS_CATEGORY_ALL_LIST);
            cache.evict(sourceId);
        }catch (Exception e){
            log.info("cache evict cache name:{} error: {} !",sourceId,e.getMessage());
        }
        return id;
    }

    /**
     * 修改讨论类型分组
     * 
     * @param params 讨论类型分组
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateDiscussSection(UpdateDiscussSectionDTO params)
    {
        String id=params.getId();
        String sourceId=params.getSourceId();
        String currUserId=params.getCurrUserId();
        //验证section的名称是否存在
        LambdaQueryWrapper<DiscussSection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DiscussSection::getSectionName, params.getSectionName());
        queryWrapper.eq(DiscussSection::getSourceId,params.getSourceId());
        queryWrapper.ne(DiscussSection::getObjectId,id);
        List<DiscussSection> sections=baseMapper.selectList(queryWrapper);
        if(sections!=null&&sections.size()>0){
            throw new BusinessException(ResultCodeEnum.DISCUSS_SECTION_NAME_EXIST_ERROR);
        }
        DiscussSection discussSection=new DiscussSection();
        BeanUtils.copyProperties(params,discussSection);
        discussSection.setLastModifiedBy(currUserId);
        LambdaUpdateWrapper<DiscussSection> sectionUpdateWrapper = new UpdateWrapper<DiscussSection>().lambda();
        sectionUpdateWrapper.eq(DiscussSection::getObjectId, id);
        int result=baseMapper.update(discussSection,sectionUpdateWrapper);
        if(result>0){
            List<String> categoryIdList=params.getCategoryIdList();
            discussCategoryMapper.deleteSection(id);
            if(categoryIdList!=null&&categoryIdList.size()>0){
                categoryIdList.stream().forEach(categoryId->{
                    LambdaUpdateWrapper<DiscussCategory> updateWrapper = new UpdateWrapper<DiscussCategory>().lambda();
                    updateWrapper.eq(DiscussCategory::getObjectId, categoryId);
                    updateWrapper.set(DiscussCategory::getSectionId,id);
                   /* DiscussCategory discussCategory=new DiscussCategory();
                    discussCategory.setSectionId(id);*/
                    discussCategoryMapper.update(null,updateWrapper);
                });
            }
            Cache cache=null;
            try{
                cache = cacheManager.getCache(RedisConstants.DISCUSS_CATEGORY_ALL_LIST);
                cache.evict(sourceId);
            }catch (Exception e){
                log.info("cache evict cache name:{} error: {} !",sourceId,e.getMessage());
            }
        }
        return result;
    }

    /**
     * 删除讨论类型分组信息
     * 
     * @param params 删除讨论类型分组请求信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteDiscussSectionById(DeleteResourceDTO params)
    {
        String id=params.getId();
        Integer sourceType=params.getSourceType();
        String sourceId=params.getSourceId();
        LambdaQueryWrapper<DiscussSection> queryWrapper = new LambdaQueryWrapper<DiscussSection>();
        queryWrapper.eq(DiscussSection::getObjectId, params.getId());
        int result=baseMapper.delete(queryWrapper);
        if(result>0){
            //移除此分组对应的讨论类型
            discussCategoryMapper.deleteSection(id);
            //清除缓存
            Cache cache=null;
            try{
                cache = cacheManager.getCache(RedisConstants.DISCUSS_CATEGORY_ALL_LIST);
                cache.evict(sourceId);
            }catch (Exception e){
                log.info("cache evict cache name:{} error: {} !",sourceId,e.getMessage());
            }
        }
        return  result;
    }

    @Override
    public Integer updateAuditStatus(UpdateAuditStatusDTO params) {
        LambdaUpdateWrapper<DiscussSection> updateWrapper = new UpdateWrapper<DiscussSection>().lambda();
        updateWrapper.eq(DiscussSection::getObjectId, params.getId());
        updateWrapper.set(DiscussSection::getAuditStatus, params.getAuditStatus());
        int result=baseMapper.update(null,updateWrapper);
        return result;
    }
}
